package com.example.quiz.controller;

import com.example.quiz.entity.QuestionWrapper;
import com.example.quiz.entity.QuizDTO;
import com.example.quiz.entity.Response;
import com.example.quiz.service.QuizService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/quiz")
public class QuizController {

    @Autowired
    QuizService quizService;

    @PostMapping("/create")
    public ResponseEntity<Integer> createQuiz(@RequestBody QuizDTO quizDTO) {
        try {

            ResponseEntity<Integer> quiz = quizService.createQuiz(quizDTO.getCategory(), quizDTO.getNumQuestions(), quizDTO.getTitle());
            return ResponseEntity.ok(quiz.getBody());
        } catch (Exception e) {
            System.out.println("Error creating quiz: " + e.getMessage());
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<List<QuestionWrapper>> getQuiz(@PathVariable Integer id) {
        try {
            ResponseEntity<List<QuestionWrapper>> quizQuestions = quizService.getQuizQuestions(id);
            List<QuestionWrapper> questions = quizQuestions.getBody();
            return ResponseEntity.ok(questions);
        } catch (Exception e) {
            System.out.println("Error getting quiz: " + e.getMessage());
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/submit/{id}")
    public ResponseEntity<Integer> submitQuiz(@PathVariable Integer id, @RequestBody List<Response> responses) {
        try {
            Integer score = quizService.calculateScore(id, responses);
            return ResponseEntity.ok(score);
        } catch (Exception e) {
            System.out.println("Error submitting quiz: " + e.getMessage());
            return ResponseEntity.status(500).body(null);
        }
    }


}
